//
//  Buffer.m
//  InterventixApp
//
//  Created by Diego Falcinelli on 09/05/13.
//
//

#import "Buffer.h"
#import "Define.h"
#import "Utente.h"
#import "InterventoCD.h"
#import "DettaglioCD.h"
#import "CryptoCR2.h"
#import "JsonCR2.h"
#import "SBJson.h"
#import "DateUtil.h"
#import "Syncronize.h"
#import "Reachability.h"
#import "CoreDataManager.h"
#import "Intervento.h"
#import "JSONConvert.h"
#import "JsonCR2.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "ComunicationsUtils.h"
#import "Util.h"


@implementation Buffer


-(void) startBuffer:(CoreDataManager *) coreDataManager andUser:(Utente *)u{
    self.coreDataManager = coreDataManager;
    self.user = u;
    NSInteger i = 30;
    if([[NSUserDefaults standardUserDefaults] objectForKey:@"update_interval"] != nil){
        i = [[[NSUserDefaults standardUserDefaults] objectForKey:@"update_interval"] integerValue] ;
        
        
    }
    [NSTimer scheduledTimerWithTimeInterval:i
                                     target:self
                                   selector:@selector(tickBuffer)
                                   userInfo:nil
                                    repeats:YES];
}


-(void) tickBuffer{
    if(![Util isLockBuffer]){
        Reachability *reachability = [Reachability reachabilityForInternetConnection];
        NetworkStatus internetStatus = [reachability currentReachabilityStatus];
        if (internetStatus != NotReachable) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshSyncro" object:nil userInfo:nil];
            
            //Seleziono il prossimo intervento da inviare se esistente
            self.selectIntervento = [self next];
            if(self.selectIntervento != nil){
                
                if([self.selectIntervento.cliente.buffer isEqual:@1]){
                    [self requestClient:self.selectIntervento.cliente];
                }else{
                    [self requestIntervent:self.selectIntervento];
                }
            }
        }
        else {
            NSLog(@"not-connected");
        }
    }else{
        //NSLog(@"lockBuffer");
    }
}



-(InterventoCD *) next{
    NSArray *a = [self.coreDataManager getInterventiToSend];
    for(InterventoCD *i in a){
        return i;
    }
    return nil;
}


- (void) requestClient:(ClienteCD *) client{
    self.req = @"client";
    
    NSMutableDictionary *diz = [JSONConvert convertCliente:client];
    NSString * json_req2;
    if([[self.coreDataManager calcStatusCliente:client] isEqualToString:@"NEW"]){
        json_req2 = [JsonCR2 createRequest:@"clients" action:@"add" paramters:diz iduser:self.user.idutente];
    }
    else{
        json_req2 = [JsonCR2 createRequest:@"clients" action:@"mod" paramters:diz iduser:self.user.idutente];
    }
    ASIFormDataRequest * request2 = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:[ComunicationsUtils getUrl]]];
    [request2 setDelegate:self];
    [request2 setTimeOutSeconds:30];
    [request2 setPostValue:json_req2 forKey:@"DATA"];
    [request2 startAsynchronous];
}
- (void) requestIntervent:(InterventoCD *) inter{
    self.req = @"intervent";
    
    NSMutableDictionary *diz = [JSONConvert convertIntervento:inter];
    
    NSString * json_req;
    
    
    NSLog(@"%@",[self.coreDataManager calcStatusIntervento:inter]);
    if([[self.coreDataManager calcStatusIntervento:inter] isEqualToString:@"NEW"]){
        json_req = [JsonCR2 createRequest:@"interventions" action:@"add" paramters:diz iduser:self.user.idutente];
    }
    else{
        json_req = [JsonCR2 createRequest:@"interventions" action:@"mod" paramters:diz iduser:self.user.idutente];
    }
    ASIFormDataRequest * request2 = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:[ComunicationsUtils getUrl]]];
    [request2 setDelegate:self];
    [request2 setTimeOutSeconds:30];
    [request2 setPostValue:json_req forKey:@"DATA"];
    [request2 startAsynchronous];
}


- (void)requestFinished:(ASIHTTPRequest *)request{
    if([self.req isEqualToString:@"client"]){
        //Leggo il risutato della richiesta
        NSDictionary *json = [JsonCR2 read:[request responseString]];
        NSString *response = [json objectForKey:@"response"];
        NSDictionary *req = [json objectForKey:@"request"];
        NSString *section = [req objectForKey:@"section"];
        NSString *action = [req objectForKey:@"action"];
        
        NSLog(@"REQ_END: {section: %@, action: %@}",section,action);
        
        
        if([response isEqualToString:@"success"]){
            NSLog(@"success");
            if([action isEqualToString:@"add"]){
                self.selectIntervento.cliente.idcliente = [NSNumber numberWithInteger:[[[json objectForKey:@"data"] objectForKey:@"idcliente"] intValue]];
            }
            self.selectIntervento.cliente.buffer = @0;
            [self.coreDataManager save];
            [self requestIntervent:self.selectIntervento];
        }else{
            NSLog(@"NO_SUCCESS: %@",json);
        }
    }
    
    if([self.req isEqualToString:@"intervent"]){
        //Leggo il risultato della richiesta
        NSDictionary *json = [JsonCR2 read:[request responseString]];
        NSString *response = [json objectForKey:@"response"];
        NSDictionary *req = [json objectForKey:@"request"];
        NSString *section = [req objectForKey:@"section"];
        NSString *action = [req objectForKey:@"action"];

        NSLog(@"REQ_END: {section: %@, action: %@}",section,action);
        NSLog(@"%@",json);
        
        
        if([response isEqualToString:@"success"]){
            NSLog(@"success");
            self.selectIntervento.buffer = @0;
            [self.coreDataManager save];
        }else if([response isEqualToString:@"conflict"]){
            NSLog(@"conflict intervent");
            self.selectIntervento.buffer = @0;
            self.selectIntervento.conflitto = @1;
            [self.coreDataManager save];
        }else{
            NSLog(@"NO_SUCCESS: %@",json);
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshBuffer" object:nil userInfo:nil];
    }
}

@end
